package org.anderground.modules.editor.importers.pmz.archive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;


public class PmzEntry {
	private boolean alreadyParsed = false;
	private BufferedReader reader;
	private List<EntrySection> sections = new ArrayList<EntrySection>();
	
	PmzEntry(InputStream in) {
		try {
			reader = new BufferedReader(new InputStreamReader(in,"Cp1251"));
			parse();
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		} 
	}
	
	private void parse() {
		String str=null;
		ForetellerReader r = new ForetellerReader(reader);
		reader = r;
		try {
			while(true) {if(str==null) {
				do {
					str = reader.readLine();							
				}while(str.length()==0 || str.charAt(0)!='[');
			}
			
			String name = str;
								
			EntrySection sec = new EntrySection(name, r);
			sections.add(sec);
			do {
				str = reader.readLine();
				
				
			} while(str.length()==0 || str.charAt(0)!='[');
			
			if(str.equals("[]")) break;
			
			
		}
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
			
		} 
		
	}

	public EntrySection getSection(String name) {
		if(!alreadyParsed) {
			Enumeration<? extends EntrySection> e = getSections();
			while(e.hasMoreElements()) e.nextElement();
		}
		for(EntrySection sec: sections) {
			if(sec.getName().equals(name)) {
				return sec;
			}
		}
		return null;
	}
	
	public Enumeration<? extends EntrySection> getSections() {
		final Iterator<EntrySection> iter = sections.iterator();
		return new Enumeration<? extends EntrySection>() {
			@Override
			public boolean hasMoreElements() {
				return iter.hasNext();
			}

			@Override
			public EntrySection nextElement() {
				return iter.next();
			}

		};

	}
}
